package com.example.statistics.ui.purchase

import android.os.Bundle
import com.example.statistics.R
import com.example.statistics.bean.ProductBean
import com.example.statistics.bean.PurchaseProductBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.ui.product.ProductInfoListActivity
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.example.statistics.ex.afterTextChangedListener
import com.example.statistics.ex.contentText
import com.example.statistics.ex.textStringToNumber
import com.example.statistics.ex.toUpperCase
import kotlinx.android.synthetic.main.activity_purchase_product_edit.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.startActivity

/**
 * 商品基本信息编辑
 */
class PurchaseProductEditActivity : BaseActivity() {

    private var factoryNo: String? = null
    private var productName: String? = null
    private var purchaseId = 0 //商品id
    private var productId = 0 //商品id
    private var agentId = 0 //代理id
    private var futuresSpot = "期货"
    private var isRefresh = false
    private var product: ProductBean? = null

    override val title: String
        get() = "基础信息"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_purchase_product_edit)
        val data = intent.getSerializableExtra(Constants.DATA) as PurchaseProductBean?
        tv_contract_no.toUpperCase()
        tv_container_no.toUpperCase()
        tv_agent_contract_no.toUpperCase()
        if (data != null) {//编辑
            purchaseId = data.ID
            agentId = data.agentId
            productId = data.productId
            factoryNo = data.factoryNo
            productName = data.productName
            futuresSpot = data.futuresSpot
            tv_date.contentText = data.date.goTimeFormat()
            tv_product_name.contentText = factoryNo + productName
            tv_agent_contract_no.contentText = data.agentContainerNo
            tv_container_no.contentText = data.containerNo
            tv_contract_no.contentText = data.contractNo
            tv_product_price.contentText = data.productPrice.toString()
            tv_price_unit.contentText = data.priceUnit
            tv_product_weight.contentText = data.productWeight.toString()
            tv_weight_unit.contentText = data.weightUnit
            tv_product_number.contentText = "${data.productNumber}件"
            et_remark.setText(data.remark)
            tv_total_price.contentText = data.productTotalPrice.toString()
        } else {//新增
            futuresSpot = intent.getStringExtra(Constants.ACTION) ?: "期货"
            agentId = intent.getIntExtra(Constants.PARENT_ID, -1)
            tv_price_unit.text = if (futuresSpot == "期货") "$" else "￥"
        }


        topBarRightText("保存") {
            if (isRefresh) {
                messageDialog(msg = "商品总价为${tv_total_price.contentText}，是否进行保存？") { _, _ ->
                    commit()
                }
            } else {
                commit()
            }
        }

        tv_product_name.onContentClicked {
            activityForResult<ProductInfoListActivity>(Constants.ACTION to Constants.SELECTOR) { intent ->
                product = intent?.getSerializableExtra(Constants.DATA) as ProductBean?
                product?.let {
                    productId = it.id
                    factoryNo = it.factoryNo
                    productName = it.productName
                    tv_product_name.contentText = factoryNo + productName
                }
            }
        }


        tv_price_unit.onClick {
            singleDialog("$", "￥", "€") {
                tv_price_unit.text = it
            }
        }

        tv_weight_unit.onClick {
            if (tv_weight_unit.text.toString() == "KG")
                tv_weight_unit.contentText = "磅"
            else
                tv_weight_unit.contentText = "KG"
        }
        tv_product_weight.afterTextChangedListener { editable, _ ->
            if (editable.toString().isNumber()) {
                val weight = editable.toString().toDouble()
                if (product?.specification.isNumber() || data?.specification.isNumber()) {
                    val specification = if (product?.specification.isNullOrBlank())
                        data?.specification
                    else
                        product?.specification
                    val number = weight.divEx(specification.orEmpty().toDouble(), 0)
                    tv_product_number.contentText = number.toString() + "件"
                }
                if (tv_product_price.contentText.isNumber()) {
                    val price = tv_product_price.textStringToNumber
                    tv_total_price.contentText = weight.mulEx(price).toString()
                }
            } else {
                tv_product_number.contentText = ""
                tv_total_price.contentText = "0"
            }
        }
        tv_product_price.afterTextChangedListener { editable, _ ->
            if (editable.toString().isNumber() && tv_product_weight.contentText.isNumber()) {
                val price = tv_product_price.textStringToNumber
                val weight = tv_product_weight.textStringToNumber
                tv_total_price.contentText = weight.mulEx(price).toString()
            } else {
                tv_total_price.contentText = "0"
            }
        }
    }

    private fun commit() {
        if (tv_product_name.isBlank() || tv_product_price.isBlank() || tv_product_weight.isBlank() || tv_product_number.isBlank()) {
            return
        }
        var productNumber = tv_product_number.contentText
        if (productNumber?.contains("件") == true) {
            val index = productNumber.indexOf("件")
            productNumber = productNumber.substring(0, index)
        }

        httpPost<PurchaseProductBean>(
            if (purchaseId != 0) UrlConfig.PURCHASE_PRODUCT_UPDATE else UrlConfig.PURCHASE_PRODUCT_ADD,
            config = {
                listParams = listOf(
                    "ID" to purchaseId,
                    "date" to tv_date.contentText,
                    "agentId" to agentId,
                    "productId" to productId,
                    "futuresSpot" to futuresSpot,
                    "productName" to tv_product_name.contentText,//产品名称
                    "contractNo" to tv_contract_no.contentText,//合同号
                    "containerNo" to tv_container_no.contentText,//集装箱号
                    "productPrice" to tv_product_price.contentText,//单价
                    "priceUnit" to tv_price_unit.contentText,//价格单位
                    "productWeight" to tv_product_weight.contentText,//重量
                    "weightUnit" to tv_weight_unit.contentText,//重量单位
                    "productNumber" to productNumber?.toInt(),//件数
                    "remark" to et_remark.contentText,
                    "productTotalPrice" to tv_total_price.contentText
                )
            },
            result = {
                if (purchaseId != 0) {
                    activityFinish()
                } else {
                    val rate = intent.getDoubleExtra("rate", 0.0)
                    if (futuresSpot == "期货") {
                        startActivity<PurchaseFuturesProductActivity>(
                            Constants.PURCHASE_PRODUCT_ID to it?.ID,
                            Constants.TITLE to tv_product_name.contentText,
                            "financingRate" to rate
                        )
                    } else {
                        startActivity<PurchaseSpotProductActivity>(
                            Constants.PURCHASE_PRODUCT_ID to it?.ID,
                            Constants.TITLE to tv_product_name.contentText
                        )
                    }
                    finish()
                }
            })
    }
}